import { useStorage } from "./storage";
import store from '@/store'

let baseHOST='https://saas.kf.renloong.com/app/ycMassage/';
let baseURL=`${baseHOST}api/`;
// #ifdef H5
import system from './h5/system';
// #endif
// #ifdef MP-WEIXIN
import system from './mp-weixin/system';
// #endif
if(system.isProd()){
	baseHOST=`${system.host()}/app/ycMassage/`;
	baseURL=`${system.host()}/app/ycMassage/api/`;
}
const RequestHeaders=(options)=>{
	const header={};
	if(store.getters.hasLogin){
		header['Authorization']=store.getters.getToken;
	}
	if(options&&options.header){
		for (let x in options.header) {
			header[x]=options.header[x]
		}
	}
	const storeage=useStorage();
	const appid=system.appid();
	if(appid){
		header['Appid']=appid;
		const icode=storeage.get('ICODE.'+appid);
		if(icode){
			header['Icode']=icode;
		}
		const PUID=storeage.get('PUID.'+appid);
		if(PUID){
			header['Puid']=PUID;
		}
	}
	if(store.state.GLOBALSTATUS.city.id){
		switch (store.state.GLOBALSTATUS.city.level) {
			case 0:
				header['Province']=store.state.GLOBALSTATUS.city.id;
				break;
			case 1:
				header['City']=store.state.GLOBALSTATUS.city.id;
				break;
			case 2:
				header['Area']=store.state.GLOBALSTATUS.city.id;
				break;
		}
	}
	if(store.state.GLOBALSTATUS.location){
		header['Longitude']=store.state.GLOBALSTATUS.location.longitude;
		header['Latitude']=store.state.GLOBALSTATUS.location.latitude;
	}
	return header;
}
export const buildUrl=(baseURL,url)=>{
	// 判断是否有http(s)://
	if(/http(s)?:\/\//.test(url)){
		return url;
	}
	return baseURL+url;
}
export const $http = {
    ResponseCode: {
        SUCCESS: 200,
        NEED_LOGIN: 12000,
        PAY_SUCCESS: 9000,
		PAY_NOTPAY: 11000,
		NEED_PAY:60000
    },
    baseURL,
	baseHOST,
    get: (url,options)=>{
		return new Promise((resolve,reject)=>{
			uni.request({
				...options,
				header:RequestHeaders(options),
				url:buildUrl(baseURL,url),
				success:(res)=>{
					if(res.statusCode===200){
						resolve(res.data);
					}else{
						reject(res);
					}
				},
				fail:(err)=>{
					reject(err);
				},
				complete:()=>{}
			})
		})
	},
    post: (url,options)=>{
		return new Promise((resolve,reject)=>{
			uni.request({
				...options,
				header:RequestHeaders(options),
				url:baseURL+url,
				method:'POST',
				success:(res)=>{
					if(res.statusCode===200){
						resolve(res.data);
					}else{
						reject(res);
					}
				},
				fail:(err)=>{
					reject(err);
				},
				complete:()=>{}
			})
		})
	},
	upload:(url,options)=>{
		return new Promise((resolve,reject)=>{
				uni.uploadFile({
				...options,
				header:RequestHeaders(options),
				url:baseURL+url,
				success:(res)=>{
					if(res.statusCode===200){
						resolve(JSON.parse(res.data));
					}else{
						reject(res);
					}
				},
				fail:(err)=>{
					reject(err);
				},
			})
		})
	}
}